package com.book.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author 李锦程
 * @Date 2021/4/13 11:53 上午
 * @Package com.book.util
 * @Version 1.0
 */
@Component
public class EhCacheManager {

    @Autowired
    private CacheManager manager;

    public Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        if (cache == null){
            return null;
        }
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    public void put(String cacheName, String key, Object value) {
        Cache cache = manager.getCache(cacheName);
        if (cache == null){
            return;
        }
        Element element = new Element(key, value);
        cache.put(element);
    }

    public void evict(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        if (cache == null){
            return;
        }
        cache.remove(key);
    }
}
